package com.daffodil.storage.util;

import org.springframework.beans.BeansException;
import org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext;
import org.springframework.cloud.util.ConditionalOnBootstrapEnabled;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author yweijian
 * @date 2021年12月17日
 * @version 1.0
 * @description
 */
@Slf4j
@Component
@ConditionalOnBootstrapEnabled
public class SpringBeanUtils implements ApplicationContextAware {

    private static ConfigurableApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtils.applicationContext = (ConfigurableApplicationContext) applicationContext;
    }
    
    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据类获取bean实例
     * @param clazz
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        T bean = null;
        try {
            bean = applicationContext.getBean(clazz);
        }catch (Exception e) {
            log.warn(e.getMessage());
        }
        return bean;
    }

    /**
     * 根据名称获取bean实例
     * @param name
     * @return
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        Object bean = null;
        try {
            bean  = applicationContext.getBean(name);
        }catch (Exception e) {
            log.warn(e.getMessage());
        }
        return bean;
    }
    
    /**
     * 是否是响应式应用
     * @return
     */
    public static Boolean isReactiveApplication() {
        if(applicationContext instanceof ReactiveWebServerApplicationContext) {
            return true;
        }else if(applicationContext instanceof WebApplicationContext) {
            return false;
        }else {
            return false;
        }
    }
}
